use std::error::Error;
use std::{env, fs};

pub struct Config {
    pub query: String,
    pub file_path: String,
    pub ignore_case: bool,
}

impl  Config {
    pub fn build(mut args: impl Iterator<Item=String>,) -> Result<Config, &'static str> {
         // 第一个参数是程序名，由于无需使用，因此这里直接空调用一次
        args.next(); 

        let query = match args.next() {
            Some(arg) => arg,
            None => return Err("Didn't get a query string")
            
        };
        let file_path  = match args.next() {
            Some(arg) => arg,
            None => return Err("Didn't get a file path")
        };

        let ignore_case = env::var("IGNORE_CASE").is_ok();

        Ok(Config { 
            query, 
            file_path, 
            ignore_case 
        })
    }
}

pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
    let contents = fs::read_to_string(config.file_path)
    .expect("Failed to read file");
    println!("内容:\n{contents}");
    Ok(())
}

// fn parse_config(args: &[String]) -> Config  {
//     let query = args[1].clone();
//     let file_path = args[2].clone();
//     Config { query, file_path }
// }